﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Beetle.Sl.EditorControl.Core;
using System.IO;
using Beetle.Sl.EditorControl.Controls;

namespace Beetle.Sl.EditorControl.Commands
{
    [CommandAttribute]
    public class InsertImageDocCommand : DocCommand
    {
        public override string CommandText
        {
            get
            {
                return "InsertImage";
            }
        }

        public override void Excute(object parameter)
        {
            InlineUIContainer container = new InlineUIContainer();
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "图片文件 (*.jpg)|*.jpg|图片文件 (*.jpeg)|*.jpeg|图片文件 (*.png)|*.png";

            if (openFileDialog.ShowDialog() == true)
            {
                if (openFileDialog.File != null)
                {
                    FileStream fs = openFileDialog.File.OpenRead();
                    container.Child = this.CreateImageFromUri(fs);
                    this.Editor.RichTextBoxInst.Selection.Insert(container);
                }
            }
        }

        private DocImage CreateImageFromUri(Stream stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Read(bytes, 0, bytes.Length);
            stream.Close();

            DocImage docImage = new DocImage();
            docImage.ResourceLoaded(this.Editor);
            docImage.SetBytes(Guid.NewGuid().ToString(), bytes);
            return docImage;
        }
    }
}
